package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApCollectionService;
import com.heima.article.util.ApThreadLocalUtil;
import com.heima.common.constants.ArticleContstants;
import com.heima.common.redis.CacheService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.article.pojos.ApCollection;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * APP收藏信息表 服务实现类
 * </p>
 *
 * @author itheima
 */
@Slf4j
@Service
@Transactional
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {

    private static final String COLLECTION = "collection:";

    @Autowired
    private CacheService cacheService;


    @Override
    public ResponseResult collectionArticle(CollectionBehaviorDto collectionBehaviorDto) {
        ApUser user = ApThreadLocalUtil.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        String redisKey = COLLECTION + collectionBehaviorDto.getEntryId();
        if (collectionBehaviorDto.getOperation() == ArticleContstants.FOLLOW){
            Object exist = cacheService.hGet(redisKey, user.getId().toString());
            if (exist != null){
                return ResponseResult.errorResult(AppHttpCodeEnum.ARTICLE_FOLLOW_EXIST );
            }
            cacheService.hPut(redisKey,user.getId().toString(), JSON.toJSONString(collectionBehaviorDto));
        }else {
            cacheService.hDelete(redisKey,user.getId().toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }
    }

